﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Threading;
using System.Xml;
using System.IO;

namespace 数据转换小工具
{
    public partial class ConfigForm : Form
    {
        private Calalog _localcalalog;
        private Calalog _targetcalalog;
        // 老表的所有字段
        List<Date> _oldzdlist;
        // 新表的所有字段 
        List<Date> _newzdlist;
        // 字段对应。
        Dictionary<string, string> _insertcolunmnames = new Dictionary<string, string>();
        // 新表字段对应类型。
        Dictionary<string, string> _colunmstype = new Dictionary<string, string>();
        // 新表对应替代数据
        List<string> _replacedate = new List<string>();
        private List<Relevance> _relevancelist;
        // 进度窗。
        private Progress _progress;
        // 线程
        Thread _thread;

        public bool IsAccess { get; set; }
        public ConfigForm()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 一对一表构造函数
        /// </summary>
        /// <param name="localcalalog"></param>
        /// <param name="targetcalalog"></param>
        public ConfigForm(Calalog localcalalog, Calalog targetcalalog)
        {
            InitializeComponent();
            // TODO: Complete member initialization
            this._localcalalog = localcalalog;
            this._targetcalalog = targetcalalog;
            FormInitializeOne();
            chbSelectedAll.Checked = true;
            Control.CheckForIllegalCrossThreadCalls = false;
            // 读取配置信息。
            ReadConfig();
        }
      
        /// <summary>
        /// 多对一表构造函数。
        /// </summary>
        /// <param name="localcalalog">待转表配置。</param>
        /// <param name="targetcalalog">目标表配置。</param>
        /// <param name="_relevancelist">关系</param>
        public ConfigForm(Calalog localcalalog, Calalog targetcalalog, List<Relevance> _relevancelist)
        {
            InitializeComponent();
            // TODO: Complete member initialization
            this._localcalalog = localcalalog;
            this._targetcalalog = targetcalalog;
            this._relevancelist = _relevancelist;
            FormInitializeMul();
            chbSelectedAll.Checked = true;
            Control.CheckForIllegalCrossThreadCalls = false;
            // 读取配置信息。
            ReadConfig();
        }
        /// <summary>
        /// 读取配置信息。
        /// </summary>
        private void ReadConfig()
        {
            if (!File.Exists(Application.StartupPath + "\\配置信息\\" + lbTargetTable.Text + "_" + lbLocalTable.Text + ".xml")) return;
            XmlDocument doc = new XmlDocument();          
            doc.Load(Application.StartupPath + "\\配置信息\\" + lbTargetTable.Text + "_" + lbLocalTable.Text + ".xml");
            XmlNode root = doc.FirstChild;

            for (int i = 0; i < _newzdlist.Count; i++)
            {
                ComboBox cmbTarget = panel1.Controls.Find("cmbnew" + i, false)[0] as ComboBox;
                ComboBox cmbLocal = panel1.Controls.Find("cmbold" + i, false)[0] as ComboBox;
                CheckBox chb = panel1.Controls.Find("chb" + i, false)[0] as CheckBox;
                TextBox txt = panel1.Controls.Find("txt" + i, false)[0] as TextBox;
                cmbLocal.SelectedIndex = int.Parse(root.ChildNodes[i].Attributes["oldindex"].Value);
                chb.Checked = root.ChildNodes[i].Attributes["IsChecked"].Value == "0" ? true : false;
                txt.Text = root.ChildNodes[i].Attributes["ReplaceWord"].Value;
            }
        }
        /// <summary>
        /// 多对一表数据初始化。
        /// </summary>
        private void FormInitializeMul()
        {
            lbLocalTable.Text = _localcalalog.TableName;
            lbTargetTable.Text = _targetcalalog.TableName;

            int i = 0;
            int h = 13;
            // 老表的所有字段
            _oldzdlist = new List<Date>();
            // 新表的所有字段 
            _newzdlist = new List<Date>();

            #region 加载数据库字段
            OleDbConnection conold = new OleDbConnection(_localcalalog.Sql);
            conold.Open();
            //循环表关系 获取所有表的所有字段。
            for (int index = 0; index < _relevancelist.Count; index++)
            {
                //if (index == 0)
                //{
                    // 获取关系里面第一个表的所有字段。
                    OleDbCommand comold = new OleDbCommand("select sc.[COLUMN_NAME],sc.[IS_NULLABLE],sc.[DATA_TYPE] from INFORMATION_SCHEMA.COLUMNS sc where sc.[TABLE_NAME]='" + _relevancelist[index].FirstTable + "'", conold);
                    OleDbDataReader odrold = comold.ExecuteReader();
                    while (odrold.Read())
                    {
                        _oldzdlist.Add(new Date(_relevancelist[index].FirstTable + "." + odrold[0].ToString(), odrold[1].ToString() == "YES" ? true : false, odrold[2].ToString()));
                    }
                    // 如果是最后一个关系，则需同时获取最后一个表的所有字段。
                    //if (index == _relevancelist.Count - 1)
                    //{
                    odrold.Close();
                    comold.Dispose();
                    OleDbCommand comold0 = new OleDbCommand("select sc.[COLUMN_NAME],sc.[IS_NULLABLE],sc.[DATA_TYPE] from INFORMATION_SCHEMA.COLUMNS sc where sc.[TABLE_NAME]='" + _relevancelist[index].SecondTable + "'", conold);
                    OleDbDataReader odrold0 = comold0.ExecuteReader();
                    while (odrold0.Read())
                    {
                        _oldzdlist.Add(new Date(_relevancelist[index].SecondTable + "." + odrold0[0].ToString(), odrold0[1].ToString() == "YES" ? true : false, odrold0[2].ToString()));
                    }
                    odrold0.Close();
                    comold0.Dispose();
                    //}
                //}
                //else
                //{
                //    OleDbCommand comold1 = new OleDbCommand("select sc.[COLUMN_NAME],sc.[IS_NULLABLE],sc.[DATA_TYPE] from INFORMATION_SCHEMA.COLUMNS sc where sc.[TABLE_NAME]='" + _relevancelist[index].SecondTable + "'", conold);
                //    OleDbDataReader odrold1 = comold1.ExecuteReader();
                //    while (odrold1.Read())
                //    {
                //        _oldzdlist.Add(new Date(_relevancelist[index].SecondTable + "." + odrold1[0].ToString(), odrold1[1].ToString() == "YES" ? true : false, odrold1[2].ToString()));
                //    }
                //    odrold1.Close();
                //    comold1.Dispose();
                //}
            }

            List<Date> _newoldzdlist = new List<Date>();
            for (int j = 0; j < _oldzdlist.Count; j++)
            {
                _newoldzdlist.Add(_oldzdlist[j]);
            }
            for (int j = 0; j < _newoldzdlist.Count; j++)
            {
                if (j == _newoldzdlist.Count - 1)
                    continue;
                for (int n = j + 1; n < _newoldzdlist.Count; n++)
                {
                    if (_newoldzdlist[j].ClounmName == _newoldzdlist[n].ClounmName)
                    {
                        _oldzdlist.Remove(_newoldzdlist[n]);
                    }
                }
            }

            OleDbConnection connew = new OleDbConnection(_targetcalalog.Sql);
            connew.Open();
            OleDbCommand comnew = new OleDbCommand("select sc.[COLUMN_NAME],sc.[IS_NULLABLE],sc.[DATA_TYPE] from INFORMATION_SCHEMA.COLUMNS sc where sc.[TABLE_NAME]='" + _targetcalalog.TableName + "'", connew);
            OleDbDataReader odrnew = comnew.ExecuteReader();
            while (odrnew.Read())
            {
                _newzdlist.Add(new Date(odrnew[0].ToString(), odrnew[1].ToString() == "YES" ? true : false, odrnew[2].ToString()));
            }
            #endregion

            #region 加载字段控件
            foreach (Date date in _newzdlist)
            {
                List<Date> onedate = new List<Date> { date };
                ComboBox cmbnew = new ComboBox();
                cmbnew.Parent = panel1;
                cmbnew.Name = "cmbnew" + i;
                cmbnew.Location = new Point(17, h);
                cmbnew.Size = new Size(121, 20);
                cmbnew.DataSource = onedate;
                cmbnew.DisplayMember = "ClounmName";
                cmbnew.FlatStyle = FlatStyle.Popup;
                cmbnew.Enabled = false;

                if (!date.AllowNull)
                {
                    Label lb = new Label();
                    lb.Parent = panel1;
                    lb.Text = "not";
                    lb.Location = new Point(142, h + 2);
                    lb.Width = 25;
                    lb.ForeColor = Color.Red;
                }

                ComboBox cmbold = new ComboBox();
                cmbold.Parent = panel1;
                cmbold.Name = "cmbold" + i;
                cmbold.Location = new Point(185, h);
                cmbold.Size = new Size(121, 20);
                cmbold.DataSource = _oldzdlist.ToArray();
                cmbold.DisplayMember = "ClounmName";
                if (i < _oldzdlist.Count)
                    cmbold.SelectedIndex = i;
                else
                {
                    cmbold.SelectedIndex = _oldzdlist.Count - 1;
                }

                CheckBox chb = new CheckBox();
                chb.Parent = panel1;
                chb.Name = "chb" + i;
                chb.Size = new Size(15, 14);
                chb.Location = new Point(361, h + 3);

                TextBox txt = new TextBox();
                txt.Parent = panel1;
                txt.Name = "txt" + i;
                txt.Location = new Point(458, h);
                txt.Size = new Size(109, 21);

                i++;
                h += 27;
            }
            #endregion
        }

        /// <summary>
        /// 一对一表数据初始化。
        /// </summary>
        private void FormInitializeOne()
        {
            lbLocalTable.Text = _localcalalog.TableName;
            lbTargetTable.Text = _targetcalalog.TableName;

            int i = 0;
            int h = 13;
            // 老表的所有字段
            _oldzdlist = new List<Date>();
            // 新表的所有字段 
            _newzdlist = new List<Date>();

            #region 加载数据库字段
            OleDbConnection conold = new OleDbConnection(_localcalalog.Sql);
            conold.Open();
            OleDbCommand comold = new OleDbCommand("select sc.[COLUMN_NAME],sc.[IS_NULLABLE],sc.[DATA_TYPE] from INFORMATION_SCHEMA.COLUMNS sc where sc.[TABLE_NAME]='" + _localcalalog.TableName + "'", conold);
            OleDbDataReader odrold = comold.ExecuteReader();
            while (odrold.Read())
            {
                _oldzdlist.Add(new Date(odrold[0].ToString(), odrold[1].ToString() == "YES" ? true : false, odrold[2].ToString()));
            }
            OleDbConnection connew = new OleDbConnection(_targetcalalog.Sql);
            connew.Open();
            OleDbCommand comnew = new OleDbCommand("select sc.[COLUMN_NAME],sc.[IS_NULLABLE],sc.[DATA_TYPE] from INFORMATION_SCHEMA.COLUMNS sc where sc.[TABLE_NAME]='" + _targetcalalog.TableName + "'", connew);
            OleDbDataReader odrnew = comnew.ExecuteReader();
            while (odrnew.Read())
            {
                _newzdlist.Add(new Date(odrnew[0].ToString(), odrnew[1].ToString() == "YES" ? true : false, odrnew[2].ToString()));
            }
            #endregion

            #region 加载字段控件
            foreach (Date date in _newzdlist)
            {
                List<Date> onedate = new List<Date> { date };
                ComboBox cmbnew = new ComboBox();
                cmbnew.Parent = panel1;
                cmbnew.Name = "cmbnew" + i;
                cmbnew.Location = new Point(17, h);
                cmbnew.Size = new Size(121, 20);
                cmbnew.DataSource = onedate;
                cmbnew.DisplayMember = "ClounmName";
                cmbnew.FlatStyle = FlatStyle.Popup;
                cmbnew.Enabled = false;

                if (!date.AllowNull)
                {
                    Label lb = new Label();
                    lb.Parent = panel1;
                    lb.Text = "not";
                    lb.Location = new Point(142, h + 2);
                    lb.Width = 25;
                    lb.ForeColor = Color.Red;
                }

                ComboBox cmbold = new ComboBox();
                cmbold.Parent = panel1;
                cmbold.DropDownStyle = ComboBoxStyle.DropDownList;
                cmbold.FlatStyle = FlatStyle.Popup;
                cmbold.Name = "cmbold" + i;
                cmbold.Location = new Point(185, h);
                cmbold.Size = new Size(121, 20);
                cmbold.DataSource = _oldzdlist.ToArray();
                cmbold.DisplayMember = "ClounmName";
                if (i < _oldzdlist.Count)
                    cmbold.SelectedIndex = i;
                else
                {
                    cmbold.SelectedIndex = _oldzdlist.Count - 1;
                }

                CheckBox chb = new CheckBox();
                chb.Parent = panel1;
                chb.Name = "chb" + i;
                chb.Size = new Size(15, 14);
                chb.Location = new Point(361, h + 3);

                TextBox txt = new TextBox();
                txt.Parent = panel1;
                txt.Name = "txt" + i;
                txt.Location = new Point(458, h);
                txt.Size = new Size(109, 21);

                i++;
                h += 27;

               
            }
            #endregion
        }
        /// <summary>
        /// 全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chbSelectedAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (Control control in panel1.Controls)
            {
                if (control.Name.Contains("chb"))
                {
                    (control as CheckBox).Checked = chbSelectedAll.Checked;
                }
            }
        }
    
        /// <summary>
        /// 传输。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUp_Click(object sender, EventArgs e)
        {
            _thread = new Thread(DealDate);
            _thread.Start();
            _progress = new Progress();
            _progress.Show();
        }

        private void DealDate()
        {
            int accesssum = 0;
            int failsum = 0;
            // 获取老数据
            OleDbConnection conold = new OleDbConnection(_localcalalog.Sql);
            // 插入新数据
            OleDbConnection connew = new OleDbConnection(_targetcalalog.Sql);
            try
            {
                conold.Open();        
                // 规则处理。
                getDictKey();
                // 根据规则生成sql语句
                string selectSql = "select ";
                foreach (string key in _insertcolunmnames.Keys)
                {
                    selectSql += _insertcolunmnames[key] + ",";
                }
                // 数据源所在的表
                string tableold = string.Empty;
                if (_relevancelist != null)
                {
                    selectSql = selectSql.TrimEnd(',') + " from " + _relevancelist[0].FirstTable;
                    tableold += _relevancelist[0].FirstTable + "、";
                    foreach (Relevance r in _relevancelist)
                    {
                        tableold += r.SecondTable + "、";
                        selectSql += " Left Join " + r.SecondTable + " on ";
                        foreach (string key in r.RelevanceList.Keys)
                        {
                            selectSql += r.FirstTable + "." + key + "=" + r.SecondTable + "." + r.RelevanceList[key] + " and ";
                        }
                        selectSql += "1=1";
                    }
                }
                else
                {
                    selectSql = selectSql.TrimEnd(',') + " from " + _localcalalog.TableName;
                    tableold = _localcalalog.TableName;
                }
                tableold = tableold.TrimEnd('、');

                // 设置进度条的表名
                _progress.Tableold = tableold;
                _progress.TableNew = _targetcalalog.TableName;

                #region 设置进度条最大值
                string tempSql = "select count(*) from(" + selectSql + ") as T";
                OleDbCommand comcount = new OleDbCommand(tempSql, conold);
                string allsumStr=comcount.ExecuteScalar().ToString();
                int allsum = int.Parse(allsumStr);
                _progress.AllSum = allsum;
                #endregion

                // 根据sql语句查到的数据插入到新表
                OleDbCommand comold = new OleDbCommand();
                comold.CommandText = selectSql;            

                comold.Connection = conold;
                OleDbDataReader odrold = comold.ExecuteReader();                
                connew.Open();

                string msg = string.Empty;
                while (odrold.Read())
                {
                    OleDbCommand comnew = new OleDbCommand();
                    string insertsql = "insert into " + _targetcalalog.TableName + "(";
                    string values = "values(";
                    // 参数值索引
                    int i = 1;
                    // 数据是否都符合规范
                    bool cansave = true;
                    foreach (string key in _insertcolunmnames.Keys)
                    {
                        insertsql += key + ",";
                        values += "?,";
                        string replaceStr = _replacedate[i - 1];
                        string str = odrold[i - 1].ToString();
                        if (replaceStr.Length > 0)
                        {
                            str = replaceStr.Substring(1, replaceStr.Length - 2).ToLower();
                        }
                        #region 数据类型强转
                        switch (_colunmstype[key])
                        {
                            case "uniqueidentifier":
                                {
                                    Guid id = Guid.Parse("1a54e710-b559-4766-823a-20abc90714b1");
                                    if (str == "*")
                                    {
                                        id = Guid.NewGuid();
                                    }
                                    else
                                        Guid.TryParse(str, out id);
                                    if (id == Guid.Parse("1a54e710-b559-4766-823a-20abc90714b1"))
                                    {
                                        cansave = false;
                                        msg += " 表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为Uniqueidentifier类型！";
                                        DubugLog.Dubug(DateTime.Now.ToString() + ":\r\n 表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为Uniqueidentifier类型！抱歉！");
                                    }
                                    else
                                        comnew.Parameters.AddWithValue("@P" + i, id);
                                }
                                break;
                            case "bit":
                                {
                                    if (str == "true" || str == "0")
                                        comnew.Parameters.AddWithValue("@P" + i, "0");
                                    else if (str == "false" || str == "1")
                                    {
                                        comnew.Parameters.AddWithValue("@P" + i, "1");
                                    }
                                    else if (str == string.Empty)
                                    {
                                        comnew.Parameters.AddWithValue("@P" + i, DBNull.Value);
                                    }
                                    else
                                    {
                                        cansave = false;
                                        msg += " 表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为Bit类型！";
                                        DubugLog.Dubug(DateTime.Now.ToString() + ":\r\n 表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为Bit类型！抱歉！");
                                    }
                                }
                                break;
                            case "datetime":
                                {
                                    DateTime dt = new DateTime();
                                    DateTime.TryParse(str, out dt);
                                    if (str == "*")
                                    {
                                        dt = DateTime.Now;
                                    }
                                    if (dt == new DateTime())
                                    {
                                        comnew.Parameters.AddWithValue("@P" + i,DBNull.Value);
                                        //cansave = false;
                                        //msg += " 表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为DateTime类型！";
                                        //DubugLog.Dubug(DateTime.Now.ToString() + ":\r\n 表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为DateTime类型！无能为力！");
                                    }
                                    else
                                    {
                                        comnew.Parameters.AddWithValue("@P" + i, dt);
                                    }
                                }
                                break;
                            case "int":
                                {
                                    int test = int.MinValue;
                                    int.TryParse(str, out test);
                                    if (test == int.MinValue)
                                    {
                                        cansave = false;
                                        msg += " 表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为Int类型！实在抱歉！";
                                        DubugLog.Dubug(DateTime.Now.ToString() + ":\r\n 表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为Int类型！实在抱歉！");
                                    }
                                    else
                                        comnew.Parameters.AddWithValue("@P" + i, test);
                                }
                                break;
                            case "float":
                                {
                                    float test = float.MinValue;
                                    float.TryParse(str, out test);
                                    if (test == float.MinValue)
                                    {
                                        cansave = false;
                                        msg += "表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为Float类型！";
                                        DubugLog.Dubug(DateTime.Now.ToString() + ":\r\n 表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为Float类型！抱歉！");
                                    }
                                    else
                                        comnew.Parameters.AddWithValue("@P" + i, test);
                                }
                                break;
                            case "decimal":
                                {
                                    decimal test = decimal.MinValue;
                                    decimal.TryParse(str, out test);
                                    if (test == decimal.MinValue)
                                    {
                                        cansave = false;
                                        msg += "表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为Decimal类型！";
                                        DubugLog.Dubug(DateTime.Now.ToString() + ":\r\n 表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为Decimal类型！抱歉！");
                                    }
                                    else
                                        comnew.Parameters.AddWithValue("@P" + i, test);
                                }
                                break;

                            case "image":
                                {
                                    byte[] bytStr = (byte[])odrold[i - 1];
                                    //Image test =new Image;
                                    //Image.TryParse(str, out test);
                                    //if (test == decimal.MinValue)
                                    //{
                                    //    cansave = false;
                                    //    msg += "表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为Decimal类型！";
                                    //    DubugLog.Dubug(DateTime.Now.ToString() + ":\r\n 表名:" + _localcalalog.TableName == string.Empty ? _insertcolunmnames[key].Split('.')[0] : _localcalalog.TableName + " 里面的字段名：" + _insertcolunmnames[key] + " 的值为：" + str + "无法转换为Decimal类型！抱歉！");
                                    //}
                                    //else
                                    comnew.Parameters.AddWithValue("@P" + i, bytStr);
                                }
                                break;
                            default:
                                {
                                    comnew.Parameters.AddWithValue("@P" + i, str);
                                }
                                break;
                        }
                        #endregion
                        i++;
                    }
                    if (cansave)
                    {
                        insertsql = insertsql.TrimEnd(',') + ") ";
                        values = values.TrimEnd(',') + ")";
                        comnew.CommandText = insertsql + values;
                        comnew.Connection = connew;
                        comnew.ExecuteNonQuery();
                        accesssum++;
                        _progress.SuccessSum = accesssum;
                    }
                    else
                    {
                        failsum++;
                        _progress.FailSum = failsum;
                    }
                }
                conold.Close();
                connew.Close();
                if (msg.Length > 0)
                {
                    MessageBox.Show(msg);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                conold.Close();
                connew.Close();
            }
        }

        /// <summary>
        /// 获取要转换的列、同时将新表的列对应的类型 加入到字典集合中。
        /// </summary>
        private void getDictKey()
        {
            XmlDocument doc = new XmlDocument();
            XmlElement root = doc.CreateElement("Root");
            

            _insertcolunmnames.Clear();
            _colunmstype.Clear();
            _replacedate.Clear();
            for (int i = 0; i < _newzdlist.Count; i++)
            {
                ComboBox cmbTarget = panel1.Controls.Find("cmbnew" + i, false)[0] as ComboBox;
                ComboBox cmbLocal = panel1.Controls.Find("cmbold" + i, false)[0] as ComboBox;
                Date datenew = cmbTarget.SelectedItem as Date;
                Date dateold = cmbLocal.SelectedItem as Date;
                CheckBox chb = panel1.Controls.Find("chb" + i, false)[0] as CheckBox;
                TextBox txt = panel1.Controls.Find("txt" + i, false)[0] as TextBox;
                XmlElement secondNode = doc.CreateElement("Node");

                //添加oldindex属性
                XmlAttribute attr12 = doc.CreateAttribute("oldindex");
                attr12.Value = cmbLocal.SelectedIndex.ToString();
                secondNode.Attributes.Append(attr12);

                //添加IsChecked属性
                XmlAttribute attr13 = doc.CreateAttribute("IsChecked");
                attr13.Value = chb.Checked ? "0" : "1";
                secondNode.Attributes.Append(attr13);

                //添加ReplaceWord属性
                XmlAttribute attr14 = doc.CreateAttribute("ReplaceWord");
                attr14.Value = txt.Text;
                secondNode.Attributes.Append(attr14);

                root.AppendChild(secondNode);

                if (chb.Checked)
                {
                    _insertcolunmnames.Add(datenew.ClounmName, dateold.ClounmName + " as '" + i.ToString()+i.ToString()+i.ToString()+"'");
                    _colunmstype.Add(datenew.ClounmName, datenew.DateType);
                    _replacedate.Add(txt.Text);
                }
                else //当目标表的字段不可为空却没有勾选 要提示！
                {
                    if (!datenew.AllowNull && datenew.DateType != "timestamp")
                    {
                        MessageBox.Show(datenew.ClounmName + "字段是不可为空的,必须要勾选！！");
                        //return;
                    }
                }
            }
            doc.AppendChild(root);
            doc.Save(Application.StartupPath + "\\配置信息\\" + lbTargetTable.Text+"_"+lbLocalTable.Text+".xml");
        }

        /// <summary>
        /// 关闭窗体。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConfigForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_thread != null)
            {
                _thread.Abort();
            }
        }
    }

 
}
